package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.mail.MessagingException;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.email.Mail;
import com.conversationboard.model.User;
import com.conversationboard.password.PasswordGenerator;

@WebServlet(name = "ForgottenPasswordControllerServlet", urlPatterns = "/ForgottenPasswordControllerServlet")
public class ForgottenPasswordControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -7689573537227060784L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String userId = (String) request.getParameter("username");

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			User user = User.get(userId);

			if (user == null) {
				String message = "This user does not exist in the database. You may <a href='" + Configuration.getInstance().getRoot() + "/Pages/register.jsp'>register here</a>. ";
				request.setAttribute("message", message);
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				dispatcher.forward(request, response);
				return;
			}

			String emailAddress = user.getLoginId();

			/* Generate a new password */

			String password = PasswordGenerator.getPassword();

			user.changePassword(password);

			if (!emailAddress.equals("")) {
				Mail mail = new Mail();
				mail.send("noreply@pleasedonotreplytothisemail.com", emailAddress, "Forgotten Password", "Your new password is: " + password);
			}

			String message = "Your new password has been emailed to your email address... Please check it shortly.";
			request.setAttribute("message", message);
			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");

			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		} catch (NamingException ne) {
			throw new ServletException(ne);
		} catch (MessagingException msge) {
			/* Don't bother reporting that */
		}

	}

}
